﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace winformLesson1
{
    public class Reflection
    {
        /// <summary>
        ///  通过反射，将IDataReader 转化为实体类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dr"></param>
        /// <returns></returns>
        public static T ReaderToModel<T>(IDataReader dr)
        {
            Type type = typeof(T);
            T model = Activator.CreateInstance<T>();
            // 根据datareader 的列数赋值给model 
            for (int i = 0; i < dr.FieldCount; i++)
            {
                // 判断当前列 是否为null 或 是否为 DbNull 
                if (!IsNullOrDbNull(dr.GetValue(i)))
                {
                    // 获取当前列名
                    PropertyInfo pi = type.GetProperty(dr.GetName(i));
                    // 转换属性 值的类型
                    object obj = Convert.ChangeType(dr.GetValue(i), pi.PropertyType);
                    // 设置属性值
                    pi.SetValue(model, obj, null);
                }
            }
            return model;
        }


        /// <summary>
        ///  判断字段值是否为NUll
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private static bool IsNullOrDbNull(object obj)
        {
            return ((obj is DBNull) || string.IsNullOrEmpty(obj.ToString())) ? true : false;
        }
}
}
